#coding:utf-8
from django.db.models.signals import post_save
from django.dispatch import receiver
import logging
from  .models import MenuModel,PermissionsModel
methods={'POST':'新增','GET':'查询','PUT':'修改','DELETE':'删除','PATCH':'局部修改'}
logger=logging.getLogger('erp')
@receiver(post_save,sender=MenuModel)#sender是谁发送的，post_save新增保存是触发,receiver接收信号
def create_menus_permissions(sender,instance,created,**kwargs): #instance传入的对象
    """
    创建信号监控函数，信号接收者收到之后自动触发。创建菜单资源对应的权限

    """
    if created:
        logger.info('创建菜单资源对应的权限')
        if isinstance(instance,MenuModel):#判断要操作的对象是不是MenuModel
            if not instance.parent: #因为没用父菜单，那么menu就是功能模块菜单对象
                permission=PermissionsModel.objects.create(name=instance.name+'的权限',is_menu=True)
                permission.menu=instance
                permission.save()
            else: #当前菜单是接口
                for method in methods.keys():
                    permission=PermissionsModel.objects.create(name=f'{methods.get(method)}'
                                                               ,is_menu=False,method=method,path=instance.url,
                                                               desc=f'{instance.name}的{methods.get(method)}的权限')
                    permission.menu=instance
                    permission.save()
        else:
            logger.warning('当前对象不是MenuModel类型')










































